const service = require('../../../../../xci/service');
let QQMapWX = require('../../../../../utils/qqmap-wx-jssdk.min.js');
let qqmapsdk = new QQMapWX({
  key: "ZCMBZ-VNI6S-EJ3OB-6ZV7C-GDKU2-7YBYQ"
});
const selectStationInfoList = service.bus.selectStationInfoList;
let timer;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    stationName: {
      type: String,
      value: null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    stationInfoList: [],
    // 搜索内容
    search_content: "",
    // 搜索内容文字长度
    search_content_length: 0,
    poi: {}
  },

  lifetimes: {
    attached() {
      // let historySearchRouteList = wx.getStorageSync('historySearchRouteList');
      // if (historySearchRouteList && historySearchRouteList.length > 0) {
      //   this.setData({
      //     historySearchRouteList
      //   })
      // }
      this.get_location();
    }
  },

  observers: {
    'stationName': function (params) { //  'params'是要监听的字段，（params）是已更新变化后的数据
      this.setData({
        search_content: this.properties.stationName
      })
      console.log("station-info");
      this.playSearch();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取 位置权限  获取当前位置
     */
    get_location() {
      let that = this;
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          that.loadDate(res.longitude, res.latitude);
        },
        fail: (res) => {
          this.getUserLocation('需要授权位置信息，用于查看附近站点!');
        }
      })
    },

    getUserLocation(e) {
      wx.showModal({
        title: '获取位置',
        confirmText: '去设置',
        showCancel: false,
        content: e,
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting["scope.userLocation"]) {
                  this.get_location();
                } else {
                  wx.showToast({
                    title: '授权失败！',
                    icon: 'fail',
                    duration: 3000
                  })
                }
              }
            })
          }
        }
      })
    },
    /**
     * 加载数据
     */
    loadDate(longitude, latitude) {
      service.bus.getStationByLonglat({
        longitude: longitude,
        latitude: latitude,
        distance: "400"
      }).then(res => {
        this.setData({
          stationInfoList: res.data
        })
        if (this.data.stationInfoList.length > 0) {
          this.data.stationInfoList.map((item, index) => {
            item.status = false;
          })
        }
        console.log("附近的站点+线路：", this.data.stationInfoList);
      })
    },
    //  输入框的值改变 就会触发的事件
    handleInput(e) {
      // 1 获取输入框的值
      let search_content = e.detail.value.replace(/\s+/g, '');
      if (search_content.length > 0) {
        this.setData({
          search_content: search_content,
          search_content_length: 1
        })
        if(timer) clearTimeout(timer);
        timer = setTimeout(()=>{this.playSearch()}, 500);
      } else {
        this.setData({
          search_content: search_content,
          search_content_length: 0
        })
        this.endSearch();
      }
    },
    // 点击搜索文字
    playSearch() {
      if (this.data.search_content == '') {
        return;
      } else {
        //拿到查的数据 然后 在list里面过滤渲染
        let that = this;
        wx.getLocation({
          type: 'wgs84',
          async success(res) {
            var longitude = res.longitude;
            var latitude = res.latitude;
            var stationName = that.data.search_content;
            var stationInfoList = await selectStationInfoList({
              longitude,
              latitude,
              stationName
            });
            that.setData({
              stationInfoList: stationInfoList.data
            })
            if (that.data.stationInfoList.length > 0) {
              that.data.stationInfoList.map((item, index) => {
                item.status = false;
              })
            }
          },
          fail: (res) => {
            this.getUserLocation('需要授权位置信息，用于查看附近站点!');
          }
        })
      }
    },
    // 点击取消按钮
    endSearch() {
      this.setData({
        search_content: ""
      })
      this.get_location();
    },
    dianji(e) {
      let stationInfoList = this.data.stationInfoList;
      let {
        i,
        s
      } = e.currentTarget.dataset;
      stationInfoList.map((item, index) => {
        if (index === i) {
          item.status = !s;
        } else {
          item.status = false;
        }
      })
      this.setData({
        stationInfoList: stationInfoList
      })
      const {
        longitude,
        latitude,
        stationname
      } = e.currentTarget.dataset;
      this.getMap(latitude, longitude, stationname);
    },
    getMap(lat, lon, title) {
      let that = this;
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: lat,
          longitude: lon
        },
        success(res) {
          var res = res.result;
          var mks = [];
          mks.push({
            title: res.address,
            id: 0,
            latitude: res.location.lat,
            longitude: res.location.lng,
            iconPath: '/images/map.png',
            width: 35,
            height: 50,
            callout: {
              content: title,
              fontSize: 16,
              padding: 10,
              borderRadius: 5,
              borderColor: "#3D72EF",
              borderWidth: 1,
              anchorY: -3,
              color: '#000000',
              display: 'ALWAYS'
            }
          });
          that.setData({
            markers: mks,
            poi: {
              latitude: res.location.lat,
              longitude: res.location.lng
            }
          });
        },
        fail(error) {
          wx.showToast({
            title: error,
            icon: "none",
            duration: 2000
          })
        }
      })
    },
    // 打开前往站点的位置导航
    playNavigate(e) {
      let that = this;
      let title = e.currentTarget.dataset.title;
      wx.showModal({
        title: "位置导航",
        content: "你确定要打开前往[ " + title + " ]的路线导航吗?",
        success(res) {
          if (res.confirm) {
            wx.openLocation({
              latitude: that.data.poi.latitude,
              longitude: that.data.poi.longitude,
              name: title,
              scale: 28
            })
          }
        }
      })
    },
    //点击线路
    clickInquireRoute(e) {
      //在搜索历史里面 选中线路
      let routeid = e.currentTarget.dataset.routeid;
      //触发父组件中的自定义事件 同时传递数据给父组件（routeid）  
      this.triggerEvent("stationInfoClickrouteid", {
        routeid
      });
    },
    goHere(e) {
      const {
        longitude,
        latitude,
        stationname
      } = e.currentTarget.dataset;
      console.log(longitude);
      wx.openLocation({
        latitude: Number(latitude),
        longitude: Number(longitude),
        scale: 28,
        name: stationname
      })
    },
  }
})